﻿import lite.mobile.lib.components.skin.UButtonSkin;
import lite.mobile.lib.utils.Delegate;
import lite.mobile.lib.components.skin.CollectionSkins;
import lite.mobile.lib.components.skin.ISkin;
import lite.mobile.lib.components.UComponent;

/**
 * @author alibber
 * @ 按钮
 */
class lite.mobile.lib.components.UButton extends UComponent {
	public function getType() : String {
		return "UButton";
	}

	public function UButton(name : String ,depth : Number) {
		super(name, depth);
	}

	/**
	 * 更替新皮肤
	 */
	public function updateSkin(skin : ISkin) : Void {
		// 创建并替换skin层
		$_skinMC.removeMovieClip();
		$_skinMC = null;
		$_skinMC = skin.achieveSkin($_coreMC, 0);
		// 附加当前状态已有状态,比如禁用或跳帧
		updateStatusSkin();
	}

	private function updateStatusSkin() : Void {
		if ($_enabled) {
			toEnabled();
		} else {
			toInvalidism();
		}
	}

	private var _callOnPress : Function ;
	public function set onPress(fun : Function) : Void {
		_callOnPress = fun ;
		if($_coreMC) {
			$_coreMC.onPress = Delegate.create(this, _callOnPress, $_coreMC) ;
		}
	}

	// 处理程序内部事件
	public function $_initEvent() : Void {
		if(!_callOnPress) {
			$_coreMC.onPress = Delegate.create(this, _callOnPress, $_coreMC) ;
		}
		$_coreMC.onSetFocus = Delegate.create(this, _onSetFocus) ;
		$_coreMC.onKillFocus = Delegate.create(this, _onKillFocus) ;
	}
	
	// 获取到焦点
	private function _onSetFocus() : Void {
		toFocus();
	}

	// 失去了焦点
	private function _onKillFocus() : Void {
		toDefault();
	}

	
	public function isEnabled() : Boolean {
		return $_enabled;
	}

	// 激活
	public function toEnabled() : Void {
		$_enabled = false ;
		if($_skinMC && $_coreMC) {
			_toEnabled();
		}
	}
	
	/**
	 * 默认状态
	 */
	public function toDefault() : Void {
		$_skinMC.gotoAndStop(UButtonSkin.DEFAULT);
	}

	/**
	 * 焦点选中状态
	 */
	public function toFocus() : Void {
		$_skinMC.gotoAndStop(UButtonSkin.FOCUS);
	}

	private function _toEnabled() : Void {
		$_skinMC.gotoAndStop(UButtonSkin.DEFAULT);
		$_coreMC.enabled = true;
	}

	/**
	 * 禁用按钮状态
	 */
	public function toInvalidism() : Void {
		$_enabled = false ;
		if($_skinMC && $_coreMC) {
			_toInvalidism();
		}
	}

	private function _toInvalidism() : Void {
		$_skinMC.gotoAndStop(UButtonSkin.INVALIDISM);
		$_coreMC.enabled = false;
	}

	public function toString2() : String {
		return this._name ;
	}
}